import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;

import java.io.*;


/**
 * rengy
 * 拷贝启动脚本插件
 */
@Mojo(name = "package",// 此Mojo对应的目标的名称
        defaultPhase = LifecyclePhase.PREPARE_PACKAGE,//设置此Mojo绑定到的phase
        requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME,
        requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME,
        requiresProject = true,//// 提示此Mojo必须在一个Maven项目内运行
        threadSafe = true//// 提示此Mojo是否线程安全，线程安全的Mojo支持在并行构建中被并发的调用
)
public class LauncherWriterMojo extends AbstractMojo {

    @Parameter(defaultValue = "${basedir}/target", required = true)
    private File outputDirectory;

    public void setOutputDirectory(File outputDirectory) {
        this.outputDirectory = outputDirectory;
    }

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {

        try {
            copy("launch.script");
            getLog().info("launch.script has been created.");
            //copy("inlined-conf.script");
            //getLog().info("inlined-conf.script has been created.");
        } catch (IOException ie) {
            throw new MojoExecutionException("拷贝launch.script文件出错!",ie);
        }

    }

    private void copy(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
    }

    private void copy(String filename) throws IOException{
        outputDirectory.mkdir();
        File target = new File(outputDirectory , filename);
//        target.setExecutable(true,false);
//        target.setWritable(true,false);
//        target.setReadable(true,false);
        try (InputStream inputStream = getClass().getResourceAsStream("/" + filename); OutputStream outputStream = new FileOutputStream(target)) {

            copy(inputStream, outputStream);
        }
    }
}